package com.zigong.app.ui.activities;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.Space;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.Log;
import android.util.Pair;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.gridsum.videotracker.entity.VideoInfo;
import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureExternalPreviewActivity;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.mob.tools.utils.DeviceHelper;
import com.ruihang.generalibrary.beans.HtmlNodeItem;
import com.ruihang.generalibrary.db.DBUtils;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.util.BitmapUtils;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.util.ViewUtils;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.DeviceUtils;
import com.ruihang.generalibrary.utils.GroupOrderHelper;
import com.ruihang.generalibrary.utils.HtmlParseUtil;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.ResultAsyncTask;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.ruihang.generalibrary.utils.TimeObserve;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.zigong.app.R;
import com.zigong.app.application.Cache;
import com.zigong.app.application.Constances;
import com.zigong.app.base.BaseCanPlayActivity;
import com.zigong.app.beans.FCollect;
import com.zigong.app.beans.FComment;
import com.zigong.app.beans.FHistory;
import com.zigong.app.beans.FNews;
import com.zigong.app.beans.NewsItem;
import com.zigong.app.beans.VoteInfo;
import com.zigong.app.beans.VoteOption;
import com.zigong.app.http.AbsListNetCallback;
import com.zigong.app.http.AbsNetCallBack;
import com.zigong.app.http.NetUtils;
import com.zigong.app.http.ParamsEditor;
import com.zigong.app.ui.adapter.NewCommentAdapter;
import com.zigong.app.ui.adapter.RelateAdapter;
import com.zigong.app.ui.adapter.VoteAdapter;
import com.zigong.app.ui.dialog.CopyTextFragment;
import com.zigong.app.ui.dialog.FontSizeDiaFragment;
import com.zigong.app.ui.util.RBaseItemDecoration;
import com.zigong.app.ui.utils.CollectionUtils;
import com.zigong.app.ui.utils.GSFPlayerScreenControllImp;
import com.zigong.app.ui.utils.GlideUtil;
import com.zigong.app.ui.utils.LivingTopControllerImp;
import com.zigong.app.ui.utils.SampleListener;
import com.zigong.app.ui.utils.SkipUtil;
import com.zigong.app.ui.utils.TitleUtils;
import com.zigong.app.ui.widget.BasePlayerView;
import com.zigong.app.ui.widget.CustomBehavior;
import com.zigong.app.ui.widget.IPlayerTimeListener;
import com.zigong.app.utils.ListTypeUtils;
import com.zigong.app.utils.UserManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Call;

import static com.zigong.app.ui.dialog.NetModeDiaFragment.NO_TAG;
import static com.zigong.app.ui.dialog.NetModeDiaFragment.OK_TAG;

/**
 * 区县新闻详情
 */
public class CountyNewsDetailActivity extends BaseCanPlayActivity implements CanRefreshLayout.OnRefreshListener, AppBarLayout.OnOffsetChangedListener {

    private static final int TYPE_DETAIL = 1;
    private static final int TYPE_COMMENT_NEW = 2;
    private static final int TYPE_RELATED = 3;
    private static final int TYPE_COMMENT_LIST = 4;

    public static final int CODE_REQUEST_PERMISSION = 421;
    public static final String EX_NEWS_ITEM = "ex_news_item";

    @BindView(R.id.news_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.newes_detail_content)
    protected LinearLayout contentLay;
    @BindView(R.id.app_bar)
    protected AppBarLayout appBarLayout;
    @BindView(R.id.toolbar_layout)
    protected CollapsingToolbarLayout collapsingToolbar;
    /**
     * 标题布局
     */
    @BindView(R.id.news_detail_top_base_lay)
    protected ViewGroup titleLay;
    @BindView(R.id.news_detail_comment_lay)
    protected ViewGroup commentLay;
    @BindView(R.id.news_detail_top_ttlay)
    protected ViewGroup topttLay;
    /**
     * 音频布局
     */
    @BindView(R.id.news_detail_top_audio_lay)
    protected ViewGroup audioLay;
    @BindView(R.id.news_detail_video_container)
    protected AbsoluteLayout videoLay;
    @BindView(R.id.news_detail_audio_player_lay)
    protected AbsoluteLayout audioPlayLay;
    @BindView(R.id.news_detail_top_img)
    protected CustomEXImageView topImg;
    @BindView(R.id.newes_detail_title)
    protected CustomFontTextView newes_title;
    @BindView(R.id.newes_detail_time)
    protected CustomFontTextView newes_time;
    @BindView(R.id.newes_detail_source)
    protected CustomFontTextView newes_source;
    @BindView(R.id.news_detail_vote_title)
    protected CustomFontTextView voteTitle;
    @BindView(R.id.news_detail_web_container)
    protected ViewGroup webContainer;
    @BindView(R.id.news_detail_top_toolbar)
    protected Toolbar toolbar;
    //    @BindView(R.id.news_detail_web)
    protected WebView webView;
    @BindView(R.id.comment_layout_write_comment)
    protected CustomFontTextView comment_et;
    @BindView(R.id.newes_detail_opinion_ll)
    protected LinearLayout opinion_ll;
    @BindView(R.id.ll)
    protected ViewGroup commentShowedLay;
    @BindView(R.id.news_detail_lay_editor)
    protected ViewGroup editorLay;
    @BindView(R.id.news_detail_editor)
    protected CustomFontTextView editor;
    @BindView(R.id.comment_layout_number)
    protected CustomFontTextView comment_number;
    @BindView(R.id.newes_detail_vote)
    protected CustomFontTextView voteBtn;
    @BindView(R.id.comment_layout_collection)
    protected TextView mBtnCollect;
    @BindView(R.id.news_detail_vote_list)
    protected RecyclerView vote_list;
    @BindView(R.id.newes_detail_comment_list)
    protected RecyclerView comment_list;
    @BindView(R.id.newes_detail_relate_list)
    protected RecyclerView newes_list;
    @BindView(R.id.news_detail_news_title)
    protected CustomFontTextView relate_title;
    @BindView(R.id.news_detail_audio_time_played)
    protected CustomFontTextView audioTime;
    @BindView(R.id.can_scroll_view)
    protected NestedScrollView scrollView;
    @BindView(R.id.news_detail_player)
    protected BasePlayerView videoPlayer;
    @BindView(R.id.news_detail_bottom_space)
    protected Space bottomSpace;

    private LinearLayoutManager manager;
    private CopyTextFragment copyTextFragment;
    private VoteAdapter voteAdapter;
    private NewCommentAdapter commentAdapter;
    private RelateAdapter relateAdapter;
    private FComment focusComment;
    private boolean isCollected = false;

    private FCollect mFCollect;

    protected String tempMediaUrl;

    //    public final String testUrl="sctv/jiaodian/1276.html";
    public final String testUrl = "sctv/jiaodian/1273.html";

    private boolean isVideoType;

    private Handler handler;

    private GroupOrderHelper groupOrderHelper;

    private FNews fNews;

    private VoteInfo voteInfo;
    /**
     * 是否需要调用投票,此属性用于在获取权限返回的判断
     */
    private boolean shouldVote;

    private GSFPlayerScreenControllImp screenControllImp;
    private LivingTopControllerImp topControllerImp;
    private int commentNumber;
    private int types = Constances.COMMENT_TYPE_NEWS;

    private int fontSize;//字体大小

    private int fontSpacing;

    private FontSizeDiaFragment fontSizeDiaFragment;
    public static final String FONT_TAG = "dia_font_size_fragment";

    private ArrayList<LocalMedia> imgs;

    private int offsetTemp;

    private CustomBehavior customBehavior;

    private String column;
    private String tag;
    private int capacity = 5;//请求数据条数
    private int indexNumber = 0;
    ArrayList<Pair<String, String>> pairsParent;
    HashMap<String, String> param;
    private String baseConstUrl;
    private boolean isCityState = false;

    public static int REQUEST_COMMENT_CODE = 505;

    private IPlayerTimeListener timeListener = new IPlayerTimeListener() {
        @Override
        public void setCurrentTimeStr(CharSequence str) {
            if (audioTime != null) {
                audioTime.setText(str);
            }
        }

        @Override
        public void setTotalTimeStr(CharSequence str) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        baseUrl = getIntent().getStringExtra(EX_URL);
        param = (HashMap<String, String>) getIntent().getSerializableExtra("TAG");
        isCityState = getIntent().getBooleanExtra("IS_CITY_STATE", false);
        if (isCityState) {
            baseConstUrl = Cache.getInstance().getChoosedCityStUrl();
        }

        commentShowedLay.setVisibility(View.GONE);
        if (param != null) {
            pairsParent = new ArrayList<>();
            Iterator<HashMap.Entry<String, String>> it = param.entrySet().iterator();
            while (it.hasNext()) {
                HashMap.Entry<String, String> entry = it.next();
                pairsParent.add(new Pair<String, String>(entry.getKey(), entry.getValue()));
            }
        }
        if (TextUtils.isEmpty(baseUrl)) {
            toast(R.string.loading_invalid_data);
            finish();
            return;
        }
//        saveHistories(mFCollect);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        groupOrderHelper = new GroupOrderHelper();
        handler = new Handler();
//        newsType = getIntent().getIntExtra(EX_TYPE_NEWS, Constances.NEWS_TYPE_GRAPHIC);
        initView();
//        getNewesDetail(null);
//        getContentH5("sctv/jiaodian/1276.html");
//        webView.loadUrl(UrlUtils.linkUrls(Constances.ST_BASE_URL, testUrl));
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_newes_detail);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (videoPlayer != null) {
            videoPlayer.onVideoResume();
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                WebSettings ws = webView.getSettings();
//                JLog.e("web view is " + webView.getView() + "\n" + ws.getJavaScriptEnabled() + "  ");
                if (videoPlayer == null) {
                    return;
                }
                int[] l1 = new int[2];
                videoPlayer.getLocationInWindow(l1);
                int[] l2 = new int[2];
                topImg.getLocationInWindow(l2);
                JLog.e("ttst " + videoPlayer + "\n" + videoPlayer.getWidth() + "  " + videoPlayer.getHeight()
                        + "   " + topImg.getWidth() + "  " + topImg.getHeight() + "   " + l1[1] + "   " + l2[1]);
            }
        }, 1000);

    }

    @Override
    protected void onPause() {
        if (videoPlayer != null) {
            videoPlayer.onVideoPause();
        }
        super.onPause();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (checkPermission(false)) {
            if (shouldVote) {
                doVote();
            }
        } else {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
            }
        }
    }

    @Override
    protected boolean canEnableOrientationWhenPrepare() {
        return fNews != null && fNews.getNewsType() == Constances.NEWS_TYPE_VIDEO;
    }

    @Override
    protected boolean canEnableOrientationWhenResume() {
        return fNews != null && fNews.getNewsType() == Constances.NEWS_TYPE_VIDEO
                && videoPlayer != null && videoPlayer.getVisibility() == View.VISIBLE;
    }

    //    @Override
//    protected BasePlayerView initVideoPlayer() {
//        if (videoPlayer == null) {
//            videoPlayer = new BasePlayerView(this);
//        }
//        return videoPlayer;
//    }

    @Override
    protected StandardGSYVideoPlayer getVideoPlayer() {
        return videoPlayer;
    }

    @Override
    protected void onChangedToLandscape(Configuration newConfig) {
        super.onChangedToLandscape(newConfig);
//        if (titleLay != null) {
//            titleLay.setVisibility(View.GONE);
//        }
//        if (commentShowedLay != null) {
//            commentShowedLay.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void onChangedToPortrait(Configuration newConfig) {
        super.onChangedToPortrait(newConfig);
//        if (titleLay != null) {
//            titleLay.setVisibility(View.VISIBLE);
//        }
//        if (commentShowedLay != null) {
//            commentShowedLay.setVisibility(View.VISIBLE);
//        }
        if (fNews != null) {
            resetWebView(UrlUtils.linkUrls(Constances.ST_BASE_URL, fNews.getNewsContentH5()), getWebTextSize());
        }

        if (videoPlayer.isFullPlaying()) {
            if (offsetTemp != 0) {
                appBarLayout.setExpanded(true, true);
//                if (videoPlayer.getVisibility() != View.VISIBLE) {
//                    //由于appbarlayout的expanded是有动画的,所以需要延时一点来设置player的显示
//                    handler.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (isPortrait) {
//                                videoPlayer.setVisibility(View.VISIBLE);
//                                scrollView.setNestedScrollingEnabled(false);
//                            }
//                        }
//                    }, 100);
//                }

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TimeObserve.removeObserS(getOwnerName());
    }

    @Override
    protected void onUserExpired() {
        super.onUserExpired();
//        toLogin();
    }

    @Override
    public void onRefresh() {
        getNewesDetail(baseUrl);
    }

    /**
     * 获取全部数据
     *
     * @param ca
     */
    private void requestAll(int ca) {
        capacity = ca;
        indexNumber = 0;
        getCommentNews(getNewsId(), Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);
    }

    @Override
    protected void onCommentGetListSuc(int count, List<FComment> fProgrammes) {
        if (indexNumber >= count || count <= capacity) {
            commentNumber = count;
            refreshBottomCommentShowing(count);
            refreshCommentShowing(fProgrammes);
        } else {
            requestAll(count);
        }

    }

    @Override
    protected boolean onCommentNetPrepare(int mode) {
        loginMode = mode;
        if (mode == Constances.MODE_COMMENT_GET_NEW) {
            groupOrderHelper.addOne();
        }
        return super.onCommentNetPrepare(mode);
    }

    @Override
    protected void onCommentNetFinish(int mode, boolean isNetSuc) {
        if (mode == Constances.MODE_COMMENT_GET_NEW) {
            onNetFinish();
        }
        super.onCommentNetFinish(mode, isNetSuc);
    }

    @Override
    protected void onCommentSendSuc(int mode) {
        super.onCommentSendSuc(mode);
        if (TextUtils.isEmpty(baseConstUrl)) {
            getCommentNews(getNewsId(), Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);
        } else {
            getCommentNews(getNewsId(), baseConstUrl, Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);
        }
    }

    @Override
    protected void initVideoPlayer(@NonNull BasePlayerView player, VideoInfo info, boolean isLiving) {
        super.initVideoPlayer(player, info, false);
        player.setIsTouchWiget(false);
        setSampleVideoListener(new SampleListener() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
                JLog.e("aasa   in prepare");
                if (offsetTemp != 0) {
                    appBarLayout.setExpanded(true, true);
                }
                setAppbarEnable(false);
//                refreshLayout.setAppbarDownAlwaysExpended(true);
//                if (customBehavior!=null){
//                    customBehavior.setSkipTouch(true);
//                }
//                collapsingToolbar.settou;
                if (!isAutoRotation()) {
                    setAutoRotation(true);
                }
            }

            @Override
            public void onClickStop(String url, Object... objects) {
                super.onClickStop(url, objects);
                JLog.e("aasa   in click stop");
                setAppbarEnable(true);
            }

            @Override
            public void onAutoComplete(String url, Object... objects) {
                super.onAutoComplete(url, objects);
                JLog.e("aasa   in auto complete");
                setAppbarEnable(true);
            }

            @Override
            public void onPlayError(String url, Object... objects) {
                super.onPlayError(url, objects);
                JLog.e("aasa   in error");
                setAppbarEnable(true);
            }

            @Override
            public void onClickStartIcon(String url, Object... objects) {
                super.onClickStartIcon(url, objects);
                JLog.e("aasa   in click start icon");
            }

            @Override
            public void onClickResume(String url, Object... objects) {
                super.onClickResume(url, objects);
                JLog.e("aasa   in clickResume");
                if (offsetTemp != 0) {
                    appBarLayout.setExpanded(true, true);
                }
                if (!isAutoRotation()) {
                    setAutoRotation(true);
                }
                setAppbarEnable(false);
            }
        });
    }

    @Override
    protected void onLoginSuc() {
        super.onLoginSuc();
        if (loginMode == Constances.MODE_COMMENT_SEND_COMMENT || loginMode == Constances.MODE_COMMENT_SEND_NEWS) {
            if (commentDiaFragment != null && commentDiaFragment.isResumed()) {
                commentDiaFragment.onLoginSuc();
            }
        } else if (loginMode == 54) {
            doVote();
        }
        loginMode = 0;
    }

    @Override
    protected void onCollectCheckResult(int result) {
        setBtnCollectStyle(result > 0);
    }

    private int height = -1;
    private boolean isFirst = true;

    private void initView() {
//        setBtnCollectStyle(CollectionUtils.getInstance().isCollected(mFCollect.getId()));

        customBehavior = (CustomBehavior) ((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).getBehavior();
        refreshLayout.setAppbarUpAlwaysExpended(true);
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        newes_list.setItemAnimator(new DefaultItemAnimator());
        newes_list.addItemDecoration(new RBaseItemDecoration(2));
        newes_list.setLayoutManager(manager);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        newes_list.setHasFixedSize(true);
        newes_list.setNestedScrollingEnabled(false);
        fontSize = SharedPreferencesUtil.getSharedPreferenceInstance(this).getInt(Constances.FONT_KEY, Constances.MID_FONT);

//        webView.loadUrl("file:///android_asset/testH.html");

        refreshLayout.setOnRefreshListener(this);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        ViewGroup.LayoutParams params = appBarLayout.getLayoutParams();
        params.width = width;
        height = (int) (width * 9.0f / 16);
        params.height = height;
        appBarLayout.setLayoutParams(params);
//        ViewUtils.resetSizeRatio(appBarLayout, 16, 9);

        toolbar.setTitle("");

        collapsingToolbar.setTitle("");
        collapsingToolbar.setTitleEnabled(false);

        appBarLayout.addOnOffsetChangedListener(this);

//        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        refreshLayout.autoRefresh();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (videoPlayer != null && isVideoType) {
            videoPlayer.onConfigurationChanged(this, newConfig, null);
        }
        if (webView != null) {
            webView.reload();
        }
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//        JLog.e("vertical offset=" + verticalOffset + "   " + appBarLayout.getTotalScrollRange()
//                + "  " + topttLay.getVisibility());
        offsetTemp = verticalOffset;
        if (floatVideoUtils != null) {
            floatVideoUtils.scrollTo(0, -verticalOffset);
        }
        if (refreshLayout != null) {
            refreshLayout.setAppbarOffset(offsetTemp);
        }
        if (verticalOffset == 0) {
            topttLay.setVisibility(View.GONE);
            toolbar.setBackgroundResource(R.color.trans);
            toolbar.setVisibility(View.GONE);
//            titleTx.setText("");
//            toolbar.setNavigationIcon(R.drawable.selector_player_back);
//            collapsingToolbarLayout.setTitle("");
//            if (!refreshLayout.){
//                refreshLayout.setPullRefreshEnable(true);
//            }
        } else if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
            topttLay.setVisibility(View.VISIBLE);
            toolbar.setBackgroundResource(R.color.colorBlackTrans20);
            toolbar.setVisibility(View.VISIBLE);
            if (isAutoRotation()) {
                setAutoRotation(false);
            }
//            if (floatVideoUtils != null) {
//                if (floatVideoUtils.isPlayed()) {
//                    videoPlayer.setVisibility(View.GONE);
////                    JLog.e("rrsr  has set player Gone");
//                    topImg.setVisibility(View.VISIBLE);
//                    if (isPortrait) {
//                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
//                    } else {
//                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//                    }
//                }
//            }
//            titleTx.setText(titleStr);
//            toolbar.setNavigationIcon(R.drawable.icon_back_white);
//            collapsingToolbarLayout.setTitle(titleStr);
//            if (!refreshLayout.isRefreshing()){
//                refreshLayout.setPullRefreshEnable(false);
//            }
        } else {
            topttLay.setVisibility(View.GONE);
            toolbar.setBackgroundResource(R.color.trans);
            toolbar.setVisibility(View.GONE);
//            if (videoPlayer != null) {
//                if (videoPlayer.getVisibility() == View.VISIBLE) {
//                    topImg.setVisibility(View.INVISIBLE);
//                }
//            }
//            titleTx.setText("");
//            toolbar.setNavigationIcon(R.drawable.selector_player_back);
//            if (!refreshLayout.isRefreshing()){
//                refreshLayout.setPullRefreshEnable(false);
//            }
        }
    }

    @Override
    public void onNetPromptCallBacked(boolean isContinue) {
        if (isContinue) {
//            StandardGSYVideoPlayer player = getVideoPlayer();
            if (videoPlayer != null) {
                videoPlayer.startPlayLogic();
            }
        }
    }

    /**
     * 首次加载web，或者修改了字体大小的时候调用
     *
     * @param url web的路径
     * @param ts  字体大小
     */
    private void resetWebView(String url, WebSettings.TextSize ts) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        JLog.e("qqa  url=" + url + "\n   ts=" + ts);
        if (webView != null) {
            JLog.e("qqa has old web  " + webView);
            webView.removeJavascriptInterface("jsObj");
            webView.setWebChromeClient(null);
            webView.setWebViewClient(null);
//            ViewGroup.LayoutParams lpp=webContainer.getLayoutParams();
//            lpp.height=webView.getHeight();
//            webView.setLayoutParams(lpp);
            webContainer.removeView(webView);

        }
        webView = new WebView(this);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        webContainer.addView(webView, lp);
        initWebView(webView, ts);
        webView.loadUrl(url);
    }

    private WebSettings.TextSize getWebTextSize() {
        WebSettings.TextSize ts = null;
        if (fontSize == Constances.BIG_FONT) {
//                setFontSize(Constances.BIG_FONT);
            ts = WebSettings.TextSize.LARGEST;
            fontSpacing = Constances.SPACING_LARGE;
        } else if (fontSize == Constances.MID_FONT) {
//                setFontSize(Constances.MID_FONT);
            ts = WebSettings.TextSize.LARGER;
            fontSpacing = Constances.SPACING_MIDDLE;
        } else if (fontSize == Constances.SMALL_FONT) {
//                setFontSize(Constances.SMALL_FONT);
            ts = WebSettings.TextSize.NORMAL;
            fontSpacing = Constances.SPACING_SMALL;
        }
        return ts;
    }

    /**
     * 加载web页面
     *
     * @param url
     * @param hasChangeFont 是否改变了字体大小
     */
    private void setWebs(String url, boolean hasChangeFont) {
        JLog.e("qqa  url=" + url + "  has change " + hasChangeFont);
        if (hasChangeFont || webView == null) {
            resetWebView(url, getWebTextSize());
        } else {
            webView.loadUrl(url);
        }
    }

    /**
     * 选择切换字体大小的回调
     */
    private BaseDialogFragment.ICallBack fontCallback = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (webView == null) {
                return;
            }
            fontSize = msg.what;

            if (fNews != null) {
                JLog.e("qqa  will to reset web view");
                setWebs(UrlUtils.linkUrls(Constances.ST_BASE_URL, fNews.getNewsContentH5()), true);
            }

//            webView.reload();
//            webView.getView().forceLayout();
            checkWebHeght();

            JLog.e("font size=" + fontSize + "   ");
        }
    };

    /**
     * 重新刷新web的高度
     */
    private void checkWebHeght() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                JLog.e("eeae  ch=" + webView.getContentHeight());
                webView.loadUrl("javascript:jsObj.getContenttttHeight(document.body.offsetHeight)");
            }
        }, 200);
    }

    @OnClick({R.id.news_detail_top_shrink_play, R.id.news_detail_top_shrink_tx})
    public void topttClick(View v) {
        appBarLayout.setExpanded(true, true);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                actionPlay(topImg, videoLay);
                actionPlay(videoPlayer, UrlUtils.linkUrls(Constances.ST_BASE_URL, fNews.getNewsMediaUrl()), fNews.getNewsTitle(), fNews.getNewsImage(), true);
            }
        }, 200);
    }

    boolean isVoicePlay = false;

    @OnClick(R.id.news_detail_audio_play)
    public void audioPlayClick(View v) {
        if (fNews != null) {
            if (!isVoicePlay) {
                actionPlay(videoPlayer, UrlUtils.linkUrls(Constances.ST_BASE_URL, fNews.getNewsMediaUrl()), fNews.getNewsTitle(), null, true);
                isVoicePlay = true;
                if (v instanceof ImageView) {
                    ((ImageView) v).setImageResource(R.mipmap.icon_home_onair);
                }
            } else {
                videoPlayer.onVideoPause();
                isVoicePlay = false;
                if (v instanceof ImageView) {
                    ((ImageView) v).setImageResource(R.mipmap.icon_home_play);
                }
            }

        }
    }

    private void setAppbarEnable(boolean enable) {
        if (scrollView != null) {
            scrollView.setNestedScrollingEnabled(enable);
        }
        if (refreshLayout != null) {
            refreshLayout.setSkipAppbar(!enable);
        }
        if (customBehavior != null) {
            customBehavior.setSkipTouch(!enable);
        }
        bottomSpace.setVisibility(enable ? View.GONE : View.VISIBLE);
    }

    private void setFontSize(int size) {
        if (size != fontSize) {
            webView.getSettings().setDefaultFontSize(size);
            fontSize = size;
        }
    }

    private Object getHtmlObject() {
        Object insertObj = new Object() {
            @JavascriptInterface
            public String HtmlcallJava2(String s) {
                int pos = -1;
                if (!TextUtils.isEmpty(s) && ListUtils.isListValued(imgs)) {
                    s = UrlUtils.linkUrls(Constances.ST_BASE_URL, s);
                    for (int i = 0; i < imgs.size(); i++) {
                        if (TextUtils.equals(s, imgs.get(i).getPath())) {
                            pos = i;
                            break;
                        }
                    }
                }
                if (pos < 0) {
                    toast(R.string.data_wrong);
                } else {
                    Intent intent = new Intent(CountyNewsDetailActivity.this, PictureExternalPreviewActivity.class);
                    intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, imgs);
                    intent.putExtra(PictureConfig.EXTRA_POSITION, pos);
                    intent.putExtra("type", 2);
                    startActivity(intent);
                }
                return "java" + s;
            }

            @JavascriptInterface
            public void getContenttttHeight(int h) {
                int ch = webView.getContentHeight();
                JLog.e("eeae  h=" + h + "  ch=" + ch + "   " + webView.getHeight());
                if (ch > 0 && Math.abs(h + fontSpacing - ch) > 20) {
//                    resetWebHeght((int) ((h + fontSpacing) * webView.getScale()));
                }
//                if (Math.abs(h+Con))
            }
        };
        return insertObj;
    }

    @SuppressLint("JavascriptInterface")
    private void initWebView(@NonNull WebView wv, WebSettings.TextSize ts) {
        WebSettings settings = wv.getSettings();
        JLog.e("font size=" + fontSize + "   " + settings.getDefaultFontSize() + "   " + settings.getDefaultFixedFontSize());
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setJavaScriptEnabled(true);
        int dfs = settings.getDefaultFontSize();
        int dffs = settings.getDefaultFixedFontSize();
//        Message msg = new Message();
//        msg.what = fontSize;
//        fontCallback.onCallBackMsg(null, msg);
        settings.setDefaultFontSize(20);
        settings.setDefaultFixedFontSize((int) (20f * dffs / dfs));
        settings.setDefaultTextEncodingName("utf-8");
        settings.setTextSize(ts);
//        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        settings.setUseWideViewPort(true);
//        settings.setCacheMode();
        wv.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                if (!s.startsWith("http://")&&!s.startsWith("https://")) {
                    return true;
                }
                JLog.e("eese s=" + s);
                if (!TextUtils.isEmpty(s)) {
                    if (s.endsWith(".json")) {
                        toAnotherNewsDetail(s);
                    } else {
                        toH5(s);
                    }
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView webVie, String s) {
                super.onPageFinished(webVie, s);
                //这个是一定要加上那个的,配合scrollView和WebView的height=wrap_content属性使用
//                int w = View.MeasureSpec.makeMeasureSpec(0,
//                        View.MeasureSpec.UNSPECIFIED);
//                int h = View.MeasureSpec.makeMeasureSpec(0,
//                        View.MeasureSpec.UNSPECIFIED);
//                //重新测量
//                JLog.e("webView: w=" + w + " h=" + h);
//                webView.measure(w, height);
//                if (height != -1) {
//                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) webView.getLayoutParams();
//                    params.height = height;
//                    webView.setLayoutParams(params);
//                }

//                webView.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        int width = webView.getWidth();
//                        if (isFirst) {
//                            height = webView.getHeight();
//                            isFirst = false;
//                        }
//                        JLog.e("webView post: w=" + width + " h=" + height);
//                    }
//                }, 500);
            }
        });

        wv.setWebChromeClient(new WebChromeClient() {
        });

        wv.addJavascriptInterface(getHtmlObject(), "jsObj");
//        wv.addJavascriptInterface();
    }

    private void resetWebHeght(int h) {
        JLog.e("eeae  will reset web height=" + h);
        ViewGroup.LayoutParams lp = webView.getLayoutParams();
        lp.height = h;
        webView.setLayoutParams(lp);
        int w = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int wh = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        //重新测量
        JLog.e("webView: w=" + w + " h=" + wh);
        webView.measure(w, wh);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                JLog.e("eeae   af  wh=" + webView.getHeight());
            }
        }, 500);

    }

    ArrayList<Pair<String, String>> pairs;

    @OnClick({R.id.newes_detail_back, R.id.comment_layout_collection, R.id.comment_layout_share, R.id.newes_detail_font_size})
    public void topClick(View view) {
        pairs = new ArrayList<>();
        if (null != pairsParent) {
            pairs.addAll(pairsParent);
        }
        switch (view.getId()) {
            case R.id.newes_detail_back:
                onBackPressed();
                break;
            case R.id.comment_layout_collection:
                if (isCollected) {
                    pairs.add(new Pair<>("行为类型", "取消收藏"));
                } else {
                    pairs.add(new Pair<>("行为类型", "收藏"));
                }
                doCollect();
                if (null != fNews) {
                    GridsumWebDissector.getInstance().trackEvent(CountyNewsDetailActivity.this, "", fNews.getNewsTitle(), "", 200, pairs);
                }
                break;
            case R.id.comment_layout_share:
                if (fNews == null) {
                    if (refreshLayout.isRefreshing()) {
                        toast("数据加载中，请稍后重试");
                    } else {
                        toast(R.string.data_wrong);
                    }
                    return;
                }
                if (!TextUtils.isEmpty(fNews.getNewsShareUrl())) {
                    this.setNewsId(fNews.getNewsId());
                    showShareFragment(fNews, new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pair) {
                            pairs = new ArrayList<>();
                            if (null != pairsParent) {
                                pairs.addAll(pairsParent);
                            }
                            pairs.add(pair);
                            GridsumWebDissector.getInstance().trackEvent(CountyNewsDetailActivity.this, "", fNews.getNewsTitle(), "", 200, pairs);
                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }
                break;
            case R.id.newes_detail_font_size:
                showFontDialog();
                pairs.add(new Pair<>("行为类型", "设置字体大小"));
                if (null != fNews) {
                    GridsumWebDissector.getInstance().trackEvent(this, "", fNews.getNewsTitle(), "", 200, pairs);
                }
                break;
        }
    }

    @JavascriptInterface
    private void jsMethod(String s) {
        JLog.e("s");
    }

    private boolean initCollectData() {
        if (fNews == null) {
            return false;
        }
        if (mFCollect == null) {
            mFCollect = new FCollect();
            mFCollect.setId(fNews.getNewsId());
            String url = fNews.getNewsUrl();
            mFCollect.setUrl(TextUtils.isEmpty(url) ? baseUrl : url);
            mFCollect.setTitle(fNews.getNewsTitle());
            mFCollect.setImg(fNews.getNewsImage());
            mFCollect.setTime(fNews.getPubTime());
            mFCollect.setDataType(fNews.getNewsType());
            mFCollect.setNewsMediaLength(fNews.getNewsMediaLength());
            mFCollect.setLable(fNews.getLable());
        }
        return true;
    }

    private void doCollect() {
        if (!initCollectData()) {
            toast(R.string.data_wrong);
            return;
        }
        if (isCollected) {
            CollectionUtils.getInstance().removeCollection(mFCollect.getId());
            setBtnCollectStyle(false);
            toast(R.string.mine_collection_removed_toast);
        } else {
            CollectionUtils.getInstance().addCollection(mFCollect);
            setBtnCollectStyle(true);
            toast(R.string.mine_collection_succ_toast);
        }
    }

    @OnClick({R.id.newes_detail_vote, R.id.comment_layout_write_comment, R.id.comment_layout_number})
    public void newesClick(View view) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        if (null != pairsParent) {
            pairs.addAll(pairsParent);
        }
        switch (view.getId()) {
            case R.id.newes_detail_vote:
//                opinion_ll.setVisibility(View.GONE);
                doVote();
                pairs.add(new Pair<>("行为类型", "投票"));
                break;
            case R.id.comment_layout_write_comment:
                String newid = getNewsId();
                if (TextUtils.isEmpty(newid)) {
                    if (refreshLayout.isRefreshing()) {
                        toast("正在加载数据");
                    } else {
                        toast(R.string.data_wrong);
                    }
                    return;
                }
                if (TextUtils.isEmpty(baseConstUrl)) {
                    showCommentDialog(getNewsId(), null, types);  //0代表新闻评论
                } else {
                    showCommentDialog(getNewsId(), true, null, types);  //0代表新闻评论
                }

                pairs.add(new Pair<>("行为类型", "评论"));
                break;
            case R.id.comment_layout_number:
                if (commentNumber != 0) {
                    Intent intent = new Intent(this, CommentActivity.class);
                    String id = getNewsId();
                    if (TextUtils.isEmpty(id)) {
                        if (refreshLayout.isRefreshing()) {
                            toast("正在加载数据");
                        } else {
                            toast(R.string.data_wrong);
                        }
                        return;
                    }
                    intent.putExtra(EX_ID, id);
                    if (isCityState) {
                        intent.putExtra(Constances.IS_CITY_STATE, true);
                    }
                    intent.putExtra(EX_TYPE_NEWS, Constances.REQUEST_COMMENT_TYPE_NEWS);
                    intent.putExtra(EX_COMMENT_TYPE, types);
                    startActivityForResult(intent, REQUEST_COMMENT_CODE);
                    pairs.add(new Pair<>("行为类型", "评论"));
                }
                break;
        }
        if (null != fNews) {
            GridsumWebDissector.getInstance().trackEvent(CountyNewsDetailActivity.this, "", fNews.getNewsTitle(), "", 200, pairs);
        }
    }

    String[] ss = new String[]{
            "document.body.clientHeight",
            "document.body.offsetHeight",
            "document.body.scrollHeight",
            "document.body.scrollTop",
            "window.screen.availHeight"
    };

    private void logWebSome() {
        if (webView != null) {
            for (int i = 0; i < ss.length; i++) {
                webView.loadUrl("javascript:jsObj.getContenttttHeight(" + ss[i] + ")");
            }
        }
    }

    /**
     * 弹出字体大小选择框
     */
    private synchronized void showFontDialog() {
//        JLog.e("ffsf  " + isAutoRotation() + "  " + getRequestedOrientation()+"  "+ ((CoordinatorLayout.LayoutParams)appBarLayout.getLayoutParams()).getBehavior());
//        if (fontSizeDiaFragment == null) {
//        logWebSome();
//        if (webView != null) {
//            webView.loadUrl("javascript:jsObj.getContenttttHeight(document.body.offsetHeight)");
//            JLog.e("eeae  ch=" + webView.getContentHeight() + "   vh=" + webView.getHeight() + "   "
//                    + webView.getScaleY() + "  " + webView.getScaleX() + "  " + webView.getScale()+"  ");
//        }
        fontSizeDiaFragment = new FontSizeDiaFragment();
//        }
//        if (fontSizeDiaFragment.isAdded() || TimeObserve.isEarlyS(getOwnerName(), 50)) {
//            return;
//        }
        fontSizeDiaFragment.setCallBack(fontCallback);
        FragmentManager fm = getSupportFragmentManager();
        fontSizeDiaFragment.show(fm, FONT_TAG);
        fm.executePendingTransactions();
    }

    private void toAnotherNewsDetail(String url) {
        if (!TextUtils.isEmpty(url)) {
            Intent intent = new Intent(this, CountyNewsDetailActivity.class);
            intent.putExtra(EX_URL, url);
            startActivity(intent);
        }
    }

    private void toH5(String url) {
        if (!TextUtils.isEmpty(url)) {
            Intent intent = new Intent(this, H5NormalActivity.class);
            intent.putExtra(EX_TITLE, fNews.getNewsTitle());
            intent.putExtra(EX_HTML, url);
            startActivity(intent);
        }
    }

    private String contentUrl = "";

    private void getNewesDetail(String url) {
//        groupOrderHelper.addOne();
        NetUtils.getNetAdapter().getNewsInfo(getOwnerName(), url, new AbsNetCallBack<FNews>(FNews.class) {
            private boolean isCompile = true;

            @Override
            public void onSuc(FNews datas) {
//                JLog.e("visible=" + webView.getVisibility() + "\n" + datas);
//                webView.clearMatches();
                if (datas != null) {
                    if (datas.getNewsType() == Constances.NEWS_TYPE_VIDEO) {
                        //String[] videos = getResources().getStringArray(R.array.test_videos);
                        //  datas.setNewsMediaUrl(videos[(int) (Math.random() * videos.length)]);
                        datas.setNewsMediaUrl(datas.getNewsMediaUrl());
                    }
                    refreshTopShowing(datas);
                    refreshEditorShow(datas.getAuthorName());
                    String url = UrlUtils.linkUrls(Constances.ST_BASE_URL, datas.getNewsContentH5());
                    getContentH5Imags(url);
//                    webView.loadUrl(url);
                    setWebs(url, false);
                    contentUrl = url;
//                    webView.loadUrl("file:///android_asset/testH.html");
                    webView.setVisibility(View.VISIBLE);
//                    refreshRelateNews(datas.getRelateNewsList());
                    getRelateNews(datas.getKeyword(), datas.getNewsId());
                    checkCollect(getNewsId());
                    getVoteInfo();
                    if (TextUtils.isEmpty(baseConstUrl)) {
                        getCommentNews(getNewsId(), Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);
                    } else {
                        getCommentNews(getNewsId(), baseConstUrl, Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);
                    }
//                    getCommentNews(getNewsId(), Constances.REQUEST_COMMENT_TYPE_NEWS, 5, 0);
                    isCompile = false;
                } else {
                    refreshRelateNews(null);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                if (isCompile) {
                    refreshLayout.refreshComplete();
                }
//                onNetFinish();
            }
        });
    }

    private void getRelateNews(String keyword, String newsId) {
        if (TextUtils.isEmpty(newsId)) {
            refreshRelateNews(null);
            return;
        }
        if (TextUtils.isEmpty(baseConstUrl)) {
            groupOrderHelper.addOne();
            NetUtils.getNetAdapter().getRelateNews(getOwnerName(), keyword, newsId, new AbsListNetCallback<NewsItem>(ListTypeUtils.NewsItem()) {
                @Override
                public void onSuc(List<NewsItem> newsItems) {
                    if (ListUtils.isListValued(newsItems)) {
                        refreshRelateNews(newsItems);
//                    relate_title.setVisibility(View.VISIBLE);
                    } else {
                        relate_title.setVisibility(View.GONE);
                    }

                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                    refreshRelateNews(null);
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                    onNetFinish();
                }
            });
        }
    }

    private void getVoteInfo() {
        ParamsEditor pe = new ParamsEditor();
//        pe.put("newsId", mNewsItem.getNewsId());
        String did =
                DeviceHelper.getInstance(this).getDeviceId();
        if (TextUtils.isEmpty(did)) {
            did = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        }
        pe.put("newsId", getNewsId());
        pe.put("deviceId", did);
        String token = null;
        if (UserManager.isLoginS()) {
            pe.put("userId", UserManager.getInstance().getUser().getUserId());
            token = UserManager.getInstance().getToken();
        }

        if (TextUtils.isEmpty(baseConstUrl)) {
            groupOrderHelper.addOne();
            NetUtils.getNetAdapter().getVoteInfo(getOwnerName(), pe.getEncryptedParams(token), new AbsNetCallBack<VoteInfo>(VoteInfo.class) {
                @Override
                public void onSuc(VoteInfo info) {
                    refreshVoteShowing(info);
                }

                @Override
                public void onError(Throwable ex, String errorMsg, int netCode) {
                    super.onError(ex, errorMsg, netCode);
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                    onNetFinish();
                }
            });
        } else {
            //        groupOrderHelper.addOne();
//            NetUtils.getNetAdapter().getVoteInfo(getOwnerName(),baseConstUrl+"getVoteListInfo", pe.getEncryptedParams(token), new AbsNetCallBack<VoteInfo>(VoteInfo.class) {
//                @Override
//                public void onSuc(VoteInfo info) {
//                    refreshVoteShowing(info);
//                }
//
//                @Override
//                public void onError(Throwable ex, String errorMsg, int netCode) {
//                    super.onError(ex, errorMsg, netCode);
//                }
//
//                @Override
//                public void onEnd() {
//                    super.onEnd();
//                    onNetFinish();
//                }
//            });
        }

    }

    private void doVote() {
        if (voteAdapter == null || voteInfo == null) {
            toast(R.string.data_wrong);
            return;
        }

        if (!voteAdapter.hasSelector()) {
            toast(R.string.please_select_vote_option);
            return;
        }
        String str = voteAdapter.getSelectIdsStr();
        JLog.e("option id is " + str);
        if (TextUtils.isEmpty(str)) {
            toast(R.string.please_select_vote_option);
            return;
        }
        loginMode = 54;
        if (!UserManager.isLoginS() && !voteInfo.isAnonymous()) {
            toLogin();
            return;
        }
        String did =
                DeviceUtils.getUniqueId(this);
        if (TextUtils.isEmpty(did)) {
            did = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        }
        ParamsEditor pe = new ParamsEditor();
        DeviceHelper dh = DeviceHelper.getInstance(this);
        String strs = dh.getIPAddress();
        JLog.e("ip is " + strs);
        pe.put("deviceId", did);
        pe.put("ip", strs);
//        pe.put("newsId", getNewsId());
        pe.put("newsId", getNewsId());
        if (UserManager.isLoginS()) {
            strs = UserManager.getInstance().getUser().getUserId();
            pe.put("userId", strs);
            JLog.e("userid is " + strs);
        }
        pe.put("voteId", voteInfo.getVoteId());
        if (voteInfo.getVoteType() == Constances.VOTE_TYPE_RADIO) {
            pe.put("voteOptionId", str);
        } else {
            pe.put("voteOptionId", voteAdapter.getSelectIdArray());
        }
        NetUtils.getNetAdapter().accountVOte(getOwnerName(), pe.getEncryptedParams(UserManager.getInstance().getToken())
                , new AbsListNetCallback<VoteOption>(ListTypeUtils.VoteOption()) {
                    @Override
                    public void onSuc(List<VoteOption> voteOptions) {
                        int total = getPageResponse().getData().getVoteCount();
                        voteInfo.setVoteHeadCount(total);
                        voteAdapter.setState(total, voteInfo.getVoteType(), true);
                        voteAdapter.notifyDataSetChanged();
                        voteBtn.setVisibility(View.GONE);
                    }

                    @Override
                    public List<VoteOption> doInBackground(List<VoteOption> voteOptions) {
                        if (ListUtils.isListValued(voteOptions)) {
                            List<VoteOption> lvos = voteInfo.getVoteOptionsList();
                            for (int i = 0; i < voteOptions.size(); i++) {
                                VoteOption vo = voteOptions.get(i);
                                for (int j = 0; j < lvos.size(); j++) {
                                    VoteOption v = lvos.get(j);
                                    if (TextUtils.equals(v.getVoteOptionId(), vo.getVoteOptionId())) {
                                        v.setSelectedCount(vo.getSelectedCount());
                                    }
                                }
                            }
                        }
                        return super.doInBackground(voteOptions);
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                        toast(TextUtils.isEmpty(errorMsg) ? "投票失败" : errorMsg);
                    }
                });
    }

    private boolean checkPermission(boolean request) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PermissionChecker.PERMISSION_GRANTED) {
            return true;
        } else {
            if (request) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, CODE_REQUEST_PERMISSION);
            }
            return false;
        }
    }

    private String getTestVoteNewsId() {
        return "232";
    }

    //    private void getRelatedNews(String url) {
//        NetUtils.getNetAdapter().getNewsArray(url, new AbsNetCallBack<List<NewsItem>>(ListTypeUtils.NewsItem()) {
//            @Override
//            public void onSuc(List<NewsItem> newsItems) {
//                refreshRelateNews(newsItems);
//            }
//            @Override
//            public void onEnd() {
//                super.onEnd();
//                onNetFinish();
//            }
//        });
//    }

    private void getContentH5Imags(String url) {
        groupOrderHelper.addOne();
        imgs = null;
        final Call c = NetUtils.getNetAdapter().getStringContent(getOwnerName(), url, new AbsNetCallBack<String>(String.class) {

            @Override
            public void onSuc(String s) {
                JLog.e("h5 result is \n" + s);
            }

            @Override
            public String doInBackground(String s) {
                imgs = HtmlParseUtil.parseImages(s, Constances.ST_BASE_URL);
                return super.doInBackground(s);
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }

    private void getContentH5(String url) {
        final Call c = NetUtils.getNetAdapter().getStringContent(getOwnerName(), url, new AbsNetCallBack<String>(String.class) {
            @Override
            public void onSuc(String s) {
                JLog.e("h5 result is \n" + s);
                String u = (String) obj;
                if (!TextUtils.isEmpty(s)) {
                    String picHead = u.substring(0, u.lastIndexOf("/"));
//                    analysisHtml(s,picHead);
                    new ResultAsyncTask<List<HtmlNodeItem>>(s, picHead) {
                        @Override
                        protected List<HtmlNodeItem> doInBackground(Void... params) {
                            List<HtmlNodeItem> htmlNodes = null;
                            try {
                                htmlNodes = HtmlParseUtil.parseHtml((String) obj, logTag);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            return htmlNodes;
                        }

                        @Override
                        protected void onPostExecute(List<HtmlNodeItem> htmlNodeItems) {
                            super.onPostExecute(htmlNodeItems);
                            if (htmlNodeItems == null) {

                            }
                        }
                    }.ex();
                }
            }
        });
    }

    private synchronized void onNetFinish() {
        if (groupOrderHelper.removeOne()) {
            refreshLayout.refreshComplete();
        }
    }

    private void initInfo(FNews datas) {
//        webView.loadUrl(UrlUtils.linkUrls(Constances.ST_BASE_URL, datas.getNewsUrl()));
        webView.loadUrl("file:///android_asset/testH.html");
        refreshBottomCommentShowing(datas.getCommentCount());
    }

    /**
     * 处理评论数据
     *
     * @param datas
     * @return
     */
    private List<FComment> dataHandle(List<FComment> datas) {
        List<FComment> comments = new ArrayList<>();
        List<FComment> answers = new ArrayList<>();
        if (null != datas) {
            FComment comment;
            for (int i = 0; i < datas.size(); i++) {
                comment = datas.get(i);
                if (TextUtils.isEmpty(comment.getAnswerTo())) {
                    if (comments.size() < 5) {
                        comments.add(comment);
                    }
                } else {
                    answers.add(comment);
                }
            }

            for (int j = 0; j < answers.size(); j++) {
                FComment co = answers.get(j);
                JLog.e("NewsDetailActivity----", "answers  id =" + co.getAnswerToCommentId());
                for (int k = 0; k < comments.size(); k++) {
                    if (!TextUtils.isEmpty(co.getAnswerToCommentId()) && co.getAnswerToCommentId().equalsIgnoreCase(comments.get(k).getCommentId())) {
                        comments.add(k + 1, co);
                        break;
                    }
                }
            }
        }
        return comments;

    }

    private void refreshCommentShowing(List<FComment> list) {
        if (ListUtils.isListValued(list)) {
            List<FComment> dataList = dataHandle(list);
            commentLay.setVisibility(View.VISIBLE);
            if (commentAdapter == null) {
                commentAdapter = new NewCommentAdapter(this, dataList);
                comment_list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                comment_list.setItemAnimator(new DefaultItemAnimator());
//                comment_list.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
                commentAdapter.setItemInternalClick(replyItemClick);
                comment_list.setAdapter(commentAdapter);
                comment_list.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        JLog.e("comment_list: w=" + comment_list.getWidth() + " h=" + comment_list.getHeight());
                    }
                }, 500);
            } else {
                commentAdapter.setData(dataList);
            }
        } else {
            commentLay.setVisibility(View.GONE);
        }
    }

    private void refreshBottomCommentShowing(int count) {
        String str = getString(R.string.detail_comment_no);
        //  if (commentColumn != null && count > 0) {
        if (count > 0) {
            if (count > 99) {
                str = getString(R.string.detail_comment_counts);
            } else {
                str = getString(R.string.detail_comment_count, count);
            }
        }
        comment_number.setText(str);
    }

    private void refreshTopShowing(FNews fn) {
//        if (fn == null) {
//            return;
//        }
        if (fNews == null || fn != fNews) {
            fNews = fn;
        }
        if (null != fNews) {
            saveHistories(fNews);
            if (fNews.getNewsType() == Constances.NEWS_TYPE_AUDIO) {
                videoPlayer.setTimeListener(timeListener);
                audioLay.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (audioLay.getHeight() > 0) {
                            ViewGroup.LayoutParams lp = audioPlayLay.getLayoutParams();
                            lp.height = audioLay.getHeight();
                            audioPlayLay.setLayoutParams(lp);
                            audioLay.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    stMedia(audioLay, audioPlayLay);
                                }
                            }, 500);
                        }
                    }
                });
                audioLay.setVisibility(View.VISIBLE);
                isVideoType = false;
//            topImg.setVisibility(View.GONE);
            } else {
                isVideoType = fNews.getNewsType() == Constances.NEWS_TYPE_VIDEO;
                audioLay.setVisibility(View.GONE);
                if (isVideoType) {
                    appBarLayout.setVisibility(View.VISIBLE);
                    VideoInfo videoInfo = new VideoInfo("");
                    videoInfo.Cdn = "cdn";
                    videoInfo.VideoOriginalName = fNews.getNewsTitle();
                    videoInfo.VideoName = fNews.getNewsTitle();
                    videoInfo.VideoUrl = Constances.ST_BASE_URL + fNews.getNewsMediaUrl();
                    videoInfo.extendProperty1 = "四川观察APP_Android";
                    try {
                        videoInfo.extendProperty1 = "四川观察APP_Android_" + getApplicationContext().getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    videoInfo.extendProperty1 = NetUtils.GetNetName(this);
                    videoInfo.setVideoWebChannel("///");
                    initVideoPlayer(videoPlayer, videoInfo, false);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            stMedia(null, null);
                        }
                    }, 100);
                    ViewUtils.resetTo169Size(bottomSpace);
                } else {
                    topImg.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            if (topImg.getWidth() > 0) {
                                topImg.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                            }
                        }
                    });
                    topImg.setVisibility(View.VISIBLE);
                }
                GlideUtil.loadImgLarge169Def(this, fNews.getNewsImage(), topImg);
            }
            newes_title.setText(fNews.getNewsTitle());
            //长按，提示用户是否复制标题
            newes_title.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (null == copyTextFragment) {
                        copyTextFragment = new CopyTextFragment();
                    }
                    copyTextFragment.setDialogText("是否复制？");
                    copyTextFragment.setDialogBtnText("取消", "复制");
                    copyTextFragment.setCallBack(chooseCallBack);
                    copyTextFragment.show(getSupportFragmentManager(), NET_TAG);
                    return false;
                }
            });
            newes_time.setText(fNews.getPubTime());
            if (!TextUtils.isEmpty(fNews.getNewsSource())) {
                newes_source.setVisibility(View.VISIBLE);
                newes_source.setText(fNews.getNewsSource());
            }
        }
    }

    //选择处理
    BaseDialogFragment.ICallBack chooseCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == NO_TAG) {
            } else if (msg.what == OK_TAG) {
                if (null != newes_title.getText()) {
                    ClipboardManager cmb = (ClipboardManager) CountyNewsDetailActivity.this.getSystemService(Context.CLIPBOARD_SERVICE);
                    cmb.setText(newes_title.getText().toString().trim()); //将内容放入粘贴管理器,在别的地方长按选择"粘贴"即可
                }
            }
        }
    };

    private void refreshEditorShow(String str) {
        if (TextUtils.isEmpty(str)) {
            editorLay.setVisibility(View.GONE);
        } else {
            editorLay.setVisibility(View.VISIBLE);
            editor.setText(str);
        }
    }

    protected boolean isShouldMuteStart() {
        return !videoListener.isPlayed() && isVideoType;
    }

    protected int actionPlay(@NonNull BasePlayerView player, @NonNull String url, String
            title, String imgurl, boolean playnow) {
        JLog.e("ffsf   in  url=" + url + "  img=" + imgurl);
        int i = super.actionPlay(player, url, title, imgurl, playnow);
        if (i > 0) {
            tempMediaUrl = url;
        }
        return i;
    }

//    private void actionPlay(View v, AbsoluteLayout videoLayView) {
//
//        if (TextUtils.equals(videoPlayer.getOriUrl(), fNews.getNewsMediaUrl()) && videoPlayer.getCurrentState() != GSYVideoView.CURRENT_STATE_PLAYING) {
//            videoPlayer.startPlay();
//            return;
//        }
//
//        videoPlayer.setUp(fNews.getNewsMediaUrl(), false, fNews.getNewsTitle());
//        tempMediaUrl = fNews.getNewsMediaUrl();
//        if (videoListener.isPlayed() && isVideoType) {
//            videoPlayer.setMute(true);
//        }
//        videoPlayer.startPlay();
////        handler.postDelayed(new Runnable() {
////            @Override
////            public void run() {
////            }
////        }, 500);
//
//    }

    private synchronized void stMedia(View v, AbsoluteLayout videoLayView) {
        int netType = NetModeUtil.GetNetype(this);
//            actionPlay(v, videoLayView);
        boolean b = v != null && videoLayView != null;
        actionPlay(videoPlayer, UrlUtils.linkUrls(Constances.ST_BASE_URL, fNews.getNewsMediaUrl())
                , fNews.getNewsTitle(), b ? null : fNews.getNewsImage(), netType == 1);
        if (b) {
            ImageView vPlay = (ImageView) findViewById(R.id.news_detail_audio_play);
            vPlay.setImageResource(R.mipmap.icon_home_onair);
            isVoicePlay = true;
        }

        JLog.e("netType=" + netType);

    }

    private void setTitleDelayed() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (topControllerImp != null) {
                    topControllerImp.setTitle(fNews.getNewsTitle());
                }
            }
        }, 800);
    }

    private void refreshVoteShowing(VoteInfo info) {
        voteInfo = info;
        if (info == null || !ListUtils.isListValued(info.getVoteOptionsList())) {
            opinion_ll.setVisibility(View.GONE);
        } else {
            opinion_ll.setVisibility(View.VISIBLE);
            voteTitle.setText(info.getVoteTitle());
            boolean voted = info.isVoted();
            if (voteAdapter == null) {
                voteAdapter = new VoteAdapter(this, info.getVoteOptionsList());
                vote_list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                vote_list.setItemAnimator(new DefaultItemAnimator());
                voteAdapter.setState(info.getVoteHeadCount(), info.getVoteType(), voted);
                vote_list.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
                vote_list.setAdapter(voteAdapter);
            } else {
                voteAdapter.setHasVoted(voted);
                voteAdapter.setData(info.getVoteOptionsList());
            }
            voteBtn.setVisibility(voted ? View.GONE : View.VISIBLE);
        }
    }

    private void refreshRelateNews(List<NewsItem> list) {
        if (relateAdapter == null) {
            relateAdapter = new RelateAdapter(this, list);
            relateAdapter.setItemInternalClick(new OnItemInternalClick() {
                @Override
                public void onItemInternalClick(View itemView, View view, int position) {
                    SkipUtil.skipWithNewsItem(CountyNewsDetailActivity.this, relateAdapter.getItem(position), param);
                }
            });
            newes_list.setAdapter(relateAdapter);
        } else {
            relateAdapter.setData(list);
        }
        if (ListUtils.isListValued(list)) {
            newes_list.setVisibility(View.VISIBLE);
            relate_title.setVisibility(View.VISIBLE);
        } else {
            newes_list.setVisibility(View.GONE);
            relate_title.setVisibility(View.GONE);
        }
    }

    private String getNewsId() {
        if (fNews != null) {
            return fNews.getNewsId();
        } else {
            if (mFCollect != null) {
                return mFCollect.getId();
            }
        }
        return null;
    }

    private void analysisHtml(List<HtmlNodeItem> htmlNodes) {
        if (contentLay != null) {
            contentLay.removeAllViews();
        }
        if (floatVideoUtils != null) {
            floatVideoUtils.stopVideoView(false);
        }
//        if (mediaView != null) {
//            mediaView.setVisibility(View.GONE);
//        }

//        picUrls = new ArrayList<>();
//        currPosition = 0;//

        // LogUtil.e("analysisHtml", "result :" + result);
        LayoutInflater inflater = getLayoutInflater();

        for (final HtmlNodeItem item : htmlNodes) {
            View view = null;
            switch (item.getType()) {
                case HtmlNodeItem.TYPE_IMAGE:// 图片
//                    imgUrlList.add(item.getSrc());
                    view = inflater.inflate(R.layout.news_detail_image, null);
                    final ImageView img = (ImageView) view.findViewById(R.id.news_detail_content_img);

                    final GifImageView gifimg = (GifImageView) view.findViewById(R.id.img_gif);

//                    view.findViewById(R.id.img_fore_layout)
//                            .setOnClickListener(new PicOnClickListener(item.getSrc(), currPosition));
//                    currPosition++;

                    String str = UrlUtils.linkUrls(Constances.ST_BASE_URL, item.getSrc());
                    JLog.e("img src=" + str);
                    if (str.substring(item.getSrc().lastIndexOf(".") + 1).toLowerCase().equals("gif")) {
//                        img.setVisibility(View.GONE);
                        GlideUtil.getGlid(this, str).asGif().into(img);

                    } else {
//                        x.image().bind(img, item.getSrc(), BitmapUtil.imageOptions,
//                                new CustomBitmapLoadCallBack(view));
                        //Glide.with(this).load(item.getSrc()).into(img);
                        JLog.e("will glide img " + str);
//                        GlideUtils.loadImgWithBannerDef(this, str, img);
//                        Glide.with(this).load(str).asBitmap().placeholder(R.drawable.banner_default).fitCenter()
//                                .error(R.drawable.banner_default).into(img);
                        Glide.with(this).load(str).centerCrop().into(new SimpleTarget<GlideDrawable>() {
                            @Override
                            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {

                                img.setImageDrawable(BitmapUtils.zoomDrawable(resource, 600, 600));
                            }
                        });
                    }
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
//                            Intent intent = new Intent(CountyNewsDetailActivity.this, ShowPicActivity.class);
//                            intent.putExtra("currentImg", item.getSrc());
//                            intent.putStringArrayListExtra("imgUrlList", imgUrlList);
//                            startActivity(intent);
                        }
                    });
                    break;
                case HtmlNodeItem.TYPE_TEXT:// 文字
                case HtmlNodeItem.TYPE_TEX_ALIGN_CENTER:// 文字
                case HtmlNodeItem.TYPE_TEX_ALIGN_LEFT:// 文字
                case HtmlNodeItem.TYPE_TEX_ALIGN_RIGHT:// 文字

                    String htmlText = item.getText();

                    Log.w("htmlText", htmlText);
                    htmlText = htmlText.replaceAll("<p>", "");
                    htmlText = htmlText.replaceAll("</p>", "");
                    String temp = htmlText.replace("　", "");


                    if (TextUtils.isEmpty(htmlText) || TextUtils.isEmpty(temp)) {
                        break;
                    }
                    view = inflater.inflate(R.layout.news_detail_text, null);
//                    CustomFontTextView tv = (CustomFontTextView) view.findViewById(R.id.news_detail_content_text);
                    CustomFontTextView tv = (CustomFontTextView) view;
//                     tv.setSpacing(6);
                    tv.setLineSpacing(4, 1.3f);
                    String test =
                            "<a href=\"http://scgcfile.sctv.com:2225/scfouces/scgc2/News/newschannel/redian/201704/t20170430_3390208.json\">测试数据</a>";
                    tv.setText(getClickableHtml(htmlText));
                    tv.setAutoLinkMask(Linkify.WEB_URLS);
                    int fontType = (int) SharedPreferencesUtil.getParam(this, "SETTING_FONT_SIZE", 1);
//                    FontSizeScaleUtil.scaleFontSize(this, 1, fontType);
//                    float currSize = tv.getTextSize();
//                    int size = (fontType - 1) * 4;
//                    tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, currSize + size);
                    switch (fontType) {
                        case 0:
                            tv.setTextSize(18.0f);
                            break;
                        case 1:
                            tv.setTextSize(20.0f);
                            break;
                        case 2:
                            tv.setTextSize(22.0f);
                            break;
                    }
                    switch (item.getType()) {
                        case HtmlNodeItem.TYPE_TEX_ALIGN_CENTER:
                            tv.setGravity(Gravity.CENTER);
                            break;
                        case HtmlNodeItem.TYPE_TEX_ALIGN_LEFT:
                            tv.setGravity(Gravity.LEFT);
                            break;
                        case HtmlNodeItem.TYPE_TEX_ALIGN_RIGHT:
                            tv.setGravity(Gravity.RIGHT);
                            break;
                        default:
                            tv.setGravity(Gravity.LEFT);
                            break;
                    }
                    tv.setMovementMethod(LinkMovementMethod.getInstance());
                    break;
                default:
                    break;
            }
            if (view != null) {
                contentLay.addView(view);
            }

        }
//        findViewById(R.id.ll_news_detail_content).setVisibility(View.VISIBLE);
        // }
    }

    /**
     * html点击事件
     */
    private CharSequence getClickableHtml(String html) {
        Spanned spannedHtml = Html.fromHtml(html);
        SpannableStringBuilder clickableHtmlBuilder = new SpannableStringBuilder(spannedHtml);
        URLSpan[] urls = clickableHtmlBuilder.getSpans(0, spannedHtml.length(), URLSpan.class);
        for (final URLSpan span : urls) {
            setLinkClickable(clickableHtmlBuilder, span);

        }
        return clickableHtmlBuilder;
    }

    /**
     * 链接点击事件
     *
     * @param clickableHtmlBuilder
     * @param urlSpan
     */
    private void setLinkClickable(final SpannableStringBuilder clickableHtmlBuilder,
                                  final URLSpan urlSpan) {
        int start = clickableHtmlBuilder.getSpanStart(urlSpan);
        int end = clickableHtmlBuilder.getSpanEnd(urlSpan);
        int flags = clickableHtmlBuilder.getSpanFlags(urlSpan);

        ClickableSpan clickableSpan = new ClickableSpan() {
            public void onClick(View view) {
                String url = urlSpan.getURL();
                Intent intent = null;
                if (url.endsWith(".json")) {
//                    NewsData data = new NewsData();
//                    data.setNewsUrl(url);
//                    intent = new Intent(CountyNewsDetailActivity.this, CountyNewsDetailActivity.class);
//                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    intent.putExtra(EX_DATA, data);
                } else {
//                    intent = new Intent(CountyNewsDetailActivity.this, WebViewActivity.class);
//                    intent.putExtra("title", detail == null ? "" : detail.getNewsTitle());
//                    intent.putExtra("NEWS_JSON_URL", url);
                }


                startActivity(intent);
            }
        };
        clickableHtmlBuilder.setSpan(clickableSpan, start, end, flags);
    }

    OnItemInternalClick replyItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
//            FComment comment = null;
//            if (view == null) {
//                comment = (FComment) itemView.getTag(R.id.adapter_item_data_key);
//            } else {
//                comment = (FComment) itemView.getTag(R.id.adapter_item_data_key);
//            }
//            focusComment = comment;
            FComment comment = commentAdapter.getItem(position);
            if (!TextUtils.isEmpty(comment.getCommentId())) {
                showCommentDialog(getNewsId(), comment.getCommentId(), types);
            } else {
                toast("评论id为空");
            }
        }
    };

    private void setBtnCollectStyle(boolean isCollected) {
        this.isCollected = isCollected;
        mBtnCollect.setText(isCollected ? R.string.mine_collection_succ : R.string.newes_collection);
        mBtnCollect.setTextColor(ContextCompat.getColor(this, isCollected ? R.color.white : R.color.colorFontSelect));
        mBtnCollect.setBackgroundResource(isCollected ? R.drawable.bg_red_ra : R.drawable.bg_look_back);
    }

    private void saveHistories(FNews news) {
        FHistory history = new FHistory();
        history.setNewsId(news.getNewsId());
        history.setFocusNews(false);
        history.setNewsImage(news.getNewsImage());
        history.setNewsMediaLength(news.getNewsMediaLength());
        history.setNewsTitle(news.getNewsTitle());
        history.setNewsType(news.getNewsType());
        String newsurl = news.getNewsUrl();
        history.setNewsUrl(TextUtils.isEmpty(newsurl) ? baseUrl : newsurl);
        history.setPubTime(news.getPubTime());
        history.setHistoryTime(System.currentTimeMillis());
        history.setLable(news.getLable());
        history.setPubTimeTemp(new Date(System.currentTimeMillis()));
        DBUtils.getInstance().replaceAxync(history);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_COMMENT_CODE) {
            if (TextUtils.isEmpty(baseConstUrl)) {
                getCommentNews(getNewsId(), Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);
            } else {
                getCommentNews(getNewsId(), baseConstUrl, Constances.REQUEST_COMMENT_TYPE_NEWS, capacity, indexNumber);
            }
        }
    }
}
